var map = {};
var zoomLevel;
var thisPoly = [];
var thisMarker = [];
var bikeMarker = [];
var busstopsMarker = [];
var atmsMarker = [];

var restroomWomensMarker = [];
var restroomMensMarker = [];
var current_infowindow;
var markersArray = [];
var n_results_start = 0;
var n_results_rows = 10;
var tag_text = '';

var indent = "off";
var marker_override = false;

var o_initial_location = new google.maps.LatLng(43.08397722062759, -77.67605446140747);

var marker_id;
var marker_num;

var currentLocationMarker = null;
var locateMe = null;
var closeInfoWindow = false;

var server = 'http://maps.rit.edu';

var shadow = new google.maps.MarkerImage(
  server + '/images/markers/marker_shadow.png?' + version,
  new google.maps.Size(40, 34),
  new google.maps.Point(0, 0),
  new google.maps.Point(10, 34)
);

//var _gaq = _gaq || [];

function setUpGoogleAnalytics() {
    _gaq.push(['_setAccount', 'UA-10681416-1']);
    _gaq.push(['_trackPageView']);

    (function () {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);

    })();
}

function pushToGoogleAnalytics(category, action, label) {
    _gaq.push(['_trackEvent', 'map: ' + category, action, label]);
}

var tileOptions = {
    getTileUrl: function (coord, zoom) {

        //return "/images/tiles/"+zoom+"/"+coord.x+"/"+y+".png";
        var mapMinZoom = 13;
        var mapMaxZoom = 19;

        if ((zoom < mapMinZoom) || (zoom > mapMaxZoom)) { return server + "/images_not_owned_by_pat/none.png?" + version; }
        //MapTiler
        //43.0940245 43.0702105 -77.6525765 -77.6903625

        var swBound = new google.maps.LatLng(43.0702105, -77.6903625);
        var neBound = new google.maps.LatLng(43.0940245, -77.6525765);
        var go_mapBounds = new google.maps.LatLngBounds(swBound, neBound);

        var ymax = 1 << zoom;
        //var y = ymax - coord.y -1;

        var y = (Math.pow(2, zoom) - coord.y - 1);

        var zfactor = Math.pow(2, zoom);
        var go_neTileLatLng = map.getProjection().fromPointToLatLng(new google.maps.Point(coord.x * 256 / zfactor, coord.y * 256 / zfactor));
        var go_swTileLatLng = map.getProjection().fromPointToLatLng(new google.maps.Point((coord.x + 1) * 256 / zfactor, (coord.y + 1) * 256 / zfactor));
        var go_tileBounds = new google.maps.LatLngBounds(go_swTileLatLng, go_neTileLatLng);
        if (go_tileBounds.intersects(go_mapBounds)) {
            return "http://maps.rit.edu/images/tiles/" + zoom + "/" + coord.x + "/" + y + ".png";
        }
        else {
            return "http://maps.rit.edu/images/none.png?" + version;
        }
    },
    tileSize: new google.maps.Size(256, 256),
    isPng: true
};

var tileMapType = new google.maps.ImageMapType(tileOptions);

var infowindowOptions = { maxWidth: 170 };

var infowindow = new google.maps.InfoWindow(infowindowOptions);


function locateUserOnMap() {

    if (navigator.geolocation) {
        browserSupportFlag = true;
        navigator.geolocation.getCurrentPosition(function (position) {
            o_currentLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
            currentLocationMarker.setPosition(o_currentLocation);
            map.setCenter(o_currentLocation);
            //currentLocationMarker.setMap(map);
        }, function () {
            handleNoGeolocation(browserSupportFlag);
        });
    } else {
        browserSupportFlag = false;
        handleNoGeolocation(browserSupportFlag);
    }
}


function handleNoGeolocation(errorFlag) {
    if (errorFlag == true) {
        alert("The geolocation service failed. ");
    } else {
        alert("Your browser doesn't support geolocation.");
    }
}

function setupCurrentLocationMarker(vo_map, vo_initialLocation) {
    currentLocationMarker = new google.maps.Marker({
        position: vo_initialLocation,
        icon: "http://maps.google.com/mapfiles/arrow.png",
        shadow: "http://maps.google.com/mapfiles/arrowshadow.png",
        title: "Current Location",
        draggable: true
    });
}


map.initialize = function () {
    var lat;
    var lng;
    var zoomed;
    var open;
    var tags;
    var query;
    var current_infobox = 0;
    var parameters = getUrlVars();

    query = parameters['q'];
    lat = parameters['lat'];
    lng = parameters['lng'];
    zoomed = parseInt(parameters['zoom']);
    open = parameters['open'];
    tags = parameters['tags'];

    if (parameters['start']) {

        n_results_start = parseInt(parameters['start']);
    }
    if (parameters['rows']) {
        n_results_rows = parseInt(parameters['rows']);
    }

    //if zoom is not set, set the default value
    if (isNaN(zoomed)) {
        zoomed = 16;
    }

    if (!lat) {
        lat = 43.08397722062759;
    }
    if (!lng) {
        lng = -77.67605446140747;
    }
    if (query) {
        searchTerm(query, 1); //override the search zoom with the 1 flag (do not fit all markers).  this is for deep linking
    }

    var latlng = new google.maps.LatLng(lat, lng);
    var myOptions = {
        zoom: zoomed,
        minZoom: 13,
        maxZoom: 20,
        center: latlng,
        mapTypeControlOptions: {
            style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
        },
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        disableDefaultUI: true
    };

    /*var styleOpt = [
    {featureType: "poi.business",
    elementType: "labels",
    stylers: [{ visibility: "off" }]
    },
    {
    featureType: "poi.sports_complex",
    elementType: "labels",
    stylers: [{ visibility: "off" }]
    }, 
    {
    featureType: "landscape.man_made",
    elementType: "labels",
    stylers: [{ visibility: "off" }]
    }, 
    {
    featureType: "poi.park",
    elementType: "labels",
    stylers: [{ visibility: "off" }]
    }, 
    {
    featureType: "poi.place_of_worship",
    elementType: "labels",
    stylers: [{ visibility: "off" }]
    }, 
    {
    featureType: "poi.school",
    elementType: "labels",
    stylers: [{ visibility: "off" }]
    }, 
    {
    featureType: "poi.medical",
    elementType: "labels",
    stylers: [{ visibility: "off" }]
    }, 
    {
    featureType: "poi.government",
    elementType: "labels",
    stylers: [{ visibility: "off" }]
    }, 
    {
    featureType: "road.local",
    elementType: "labels",
    stylers: [{ visibility: "off" }]
    } 
    ]; */
    var styleOpt = [
             {
                 featureType: "road.local",
                 elementType: "labels",
                 stylers: [{ visibility: "off"}]
             },
             {
                 featureType: "landscape.man_made",
                 elementType: "labels",
                 stylers: [{ visibility: "off"}]
             },
             {
                 featureType: "poi",
                 stylers: [{ visibility: "off"}]
             }

         ];


    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    // map.setOptions({styles: styleOpt});

    //map tile overlay
    map.overlayMapTypes.insertAt(0, tileMapType);
/*
    //Location Service Control 
    var locateControlDiv = document.createElement('DIV');
    var locateControl = new LocateControl(locateControlDiv, map);

    locateControlDiv.index = 1;

*/
    //map.getDiv().appendChild(locateControl); 
    //map.controls[google.maps.ControlPosition.RIGHT_TOP].push(locateControlDiv);
    map.controls[google.maps.ControlPosition.LEFT_BOTTOM].push(locateControlDiv);

    $.getJSON(server + '/proxySearch/?q=*&wt=json&indent=' + indent + '&fq=polygon_id:*&rows=1000&fl=name,mdo_id,description,longitude,latitude,path,abbreviation,building_number,image', function (data) {

        var items = [];

        var n_index = 0;

        if (open) {
            if (open.charAt(0) == 'p') {
                var exploded = open.split('-');
                current_infobox = parseInt(exploded[1]);
            }
        }

        if (data.response.numFound) {

            $.each(data.response.docs, function (index, value) {
                var polyCoords = parsePolygonPath(value.path);

                var abb = "";
                if (value.abbreviation)
                    abb = value.abbreviation;

                thisPoly[value.mdo_id] = new google.maps.Polygon({
                    paths: polyCoords,
                    strokeColor: "#FFFFFF",
                    strokeOpacity: 0.00,
                    strokeWeight: 1,
                    fillColor: "#FFFFFF",
                    fillOpacity: 0.00,
                    title: value.name,
                    description: value.description,
                    lat: value.latitude,
                    lng: value.longitude,
                    id: value.mdo_id,
                    img: value.image,
                    abb: abb
                });
                thisPoly[value.mdo_id].setMap(map);

                if (open) {
                    if (current_infobox == value.mdo_id) {
                        displayMDOInfo(parseInt(value.mdo_id), 'polygon');
                    }
                }

                // Add a listener for the click event
                google.maps.event.addListener(thisPoly[value.mdo_id], 'click', showPolyInfo);
                google.maps.event.addListener(thisPoly[value.mdo_id], "mouseover", function () { this.setOptions({ fillOpacity: 0.20, strokeOpacity: 0.20 }); });
                google.maps.event.addListener(thisPoly[value.mdo_id], "mouseout", function () { this.setOptions({ fillOpacity: 0.0, strokeOpacity: 0.0 }); });
                n_index++;


            });
        }

        //map tile overlay
        //map.overlayMapTypes.insertAt(0, tileMapType);

        if (thisPoly[current_infobox]) {
            google.maps.event.trigger(thisPoly[current_infobox], "click");
        }
    }).complete(function () {

        //open info window if needed - mark type
        if (open) {
            if (open.charAt(0) == 'm') {
                var exploded = open.split('-');
                current_infobox = parseInt(exploded[1]);

                $.getJSON(server + '/proxySearch/?q=*&wt=json&indent=' + indent + '&rows=1&fq=mdo_id:' + current_infobox, function (data) {
                    //alert(data.response.numFound);
                    if (data.response.numFound) {
                        //alert(data.response.docs[0].mdo_id);
                        var markerLatlng = new google.maps.LatLng(data.response.docs[0].latitude, data.response.docs[0].longitude);
                        //add the lat and lng to search bounds
                        //search_bounds.extend(markerLatlng);
                        var abb = "";
                        if (data.response.docs[0].abbreviation)
                            abb = data.response.docs[0].abbreviation;

                        thisMarker[data.response.docs[0].mdo_id] = new google.maps.Marker({
                            position: markerLatlng,
                            map: map,
                            title: 'Marker' + getAlpha(0) + '-m',
                            icon: server + '/images/markers/dk-blue_Marker' + getAlpha(0) + '.png?' + version,
                            title: data.response.docs[0].name,
                            description: data.response.docs[0].description,
                            shadow: shadow,
                            lat: data.response.docs[0].latitude,
                            lng: data.response.docs[0].longitude,
                            id: data.response.docs[0].mdo_id,
                            img: data.response.docs[0].image,
                            abb: abb
                        });
                        markersArray.push(thisMarker[data.response.docs[0].mdo_id]);
                        google.maps.event.addListener(thisMarker[data.response.docs[0].mdo_id], 'click', showMarkerInfo);

                    }

                }).complete(function (data) {
                    //alert(data.response.numFound);
                    displayMDOInfo(current_infobox, 'marker');
                });

            }
        }


        //open info window if needed - mark type
        if (tags) {
            tag_text = tags;

            //alert("tags: " + tags);

            var exploded = tags.split('|');
            var search_url = "";

            if (n_results_start > 0)
                search_url = server + '/proxySearch/?show=next&q=*&wt=json&indent=' + indent + '&start=' + n_results_start + '&rows=' + n_results_rows + '&sort=name+asc';
            else
                search_url = server + '/proxySearch/?q=*&wt=json&indent=' + indent + '&start=' + n_results_start + '&rows=' + n_results_rows + '&sort=name+asc';

            //is this a SIS deep link
            if ((exploded.length == 2) && (exploded[0] == 'Building') && (exploded[1].length == 3)) {
                search_url = server + '/proxySearch/?q=abbreviation:' + exploded[1] + '&wt=json&indent=' + indent + '&fq=tag:Building&start=' + n_results_start + '&rows=' + n_results_rows;
            }
            else {
                $.each(exploded, function (index, value) {
                    //alert(index + " - " +value);
                    search_url += '&fq=tag:' + value;
                });
            }

            //display results no zoom

            displayResults(search_url, 18);
            //setTimeout('displayResults("' + search_url +'", 18)', 3000);
        }
    });
    setupCurrentLocationMarker(map, o_initial_location);

}

// This function picks up the click and opens the corresponding info window
function sidebarPolyClick(i) {
    google.maps.event.trigger(thisPoly[i], "click");
}


// This function picks up the click and opens the corresponding info window
function moreInfo(i, loc_name, abb) {

    if (abb.length > 0)
        getInsideBuildingInfo(i, loc_name, abb);
    else
        getMdoContent(i, loc_name);
}



function getInsideBuildingInfo(i, loc_name, abb) {
    var services = [];

    //var url = server + '/proxySearch/?q=building:' + '"' + abb + '"&wt=json&indent=on&facet=on&facet.field=tag&facet.mincount=1&rows=0';
    var url = server + '/proxySearch/?q=tag:' + '"' + abb + '"&wt=json&indent=on&facet=on&facet.field=tag&facet.mincount=1&rows=0';
    pushToGoogleAnalytics("Infopanel-facet", loc_name, url);

    $.getJSON(url, function (data) {
        if (data.response.numFound) {
            if (data.facet_counts.facet_fields.tag) {
                var key = 0;
                for (var index in data.facet_counts.facet_fields.tag) {
                    var name = data.facet_counts.facet_fields.tag[index];
                    if (name == "i_diningservicesplus" || name == "Student Services" ||
                               name == "ATM" || name == "Computer Lab" || name == "Clubs and Organizations" || name == "Conference Room" ||
                               name == "Auditorium" || name == "Retail" || name == "Recreation") {

                        var count = parseInt(index) + 1;
                        var value = data.facet_counts.facet_fields.tag[count];
                        //alert("tag: " + name + " value = " + value);
                        if (value > 0) {
                            var obj = new Object();
                            obj.name = name;
                            obj.value = value;
                            services[key] = obj;
                            key++;
                        }
                    }
                }
                services = orderDisplayServices(services);

                services[key] = restrooms("Women's Restroom");
                key++;
                services[key] = restrooms("Men's Restroom");
            }
        }

    }).complete(function (data) {

        if (services.length > 2)  // it should greater than 0 since we add women's and men's restroom
        {

            searchMoreInfo(i, services, abb, loc_name);
        }
        else {

            getMdoContent(i, loc_name)
        }
    });
}

function restrooms(name) {
    var obj = new Object();
    obj.name = name;
    obj.value = 100;
    obj.count = 0;
    return obj;
}

function findLongest(services) {
    var longestIndex = 0;
    var maxVal = parseInt(services[0].value);

    $.each(services, function (index, service) {
        if (parseInt(service.value) > maxVal) {
            longestIndex = index;
            maxVal = parseInt(service.value);
        }
    });
    return longestIndex;
}

function addTogether(services, longestIndex) {
    var sum = 0;
    $.each(services, function (index, service) {
        if (index != longestIndex) {
            sum += parseInt(service.value);
        }
    });
    return sum;
}

function orderDisplayServices(services) {
    var len = services.length;

    if (len == 1)
        services[0].display = "left";

    else if (len == 2) {
        services[0].display = "left";
        services[1].display = "right"
    }
    else if (len >= 3) {

        var longestIndex = findLongest(services);
        var sumOthers = addTogether(services, longestIndex);
        var longestVal = parseInt(services[longestIndex].value);
        if ((longestVal - sumOthers) > 0) {
            $.each(services, function (index, service) {
                if (index == longestIndex)
                    services[index].display = "left";
                else
                    service.display = "right";
            });
        }
        else {
            for (var i = 0; i < len; i = i + 2) {
                services[i].display = "left";
                var j = i + 1;
                if (j < len) {
                    services[j].display = "right";

                }
            }
        }
    }
    return services;
}

function searchMoreInfo(i, services, abb, loc_name) {
    var mdo_url = '/api/mdos/' + i + '/content';

    //var mdo_url = '/api/?mdos-'+i+'-content';
    var image;
    var building;
    var building_num;
    var history;
    var description;
    var link;

    thinking(1);

    pushToGoogleAnalytics("Infopanel", abb + " " + loc_name, mdo_url);
    $.getJSON(mdo_url, function (data) {

        $.each(data.mdo.contents, function (index, values) {
            $.each(values, function (key, val) {
                if (val.title == "Image")
                    image = val.contentValue;
                if (val.title == "Building")
                    building = val.contentValue;
                if (val.title == "Building Number")
                    building_num = val.contentValue;
                if (val.title == "History")
                    history = val.contentValue;
                if (val.title == "Description")
                    description = val.contentValue;
                if (val.title == "Link")
                    link = val.contentValue;
            });

        });

    }).complete(function () {
        var complete = 0;

        for (var index in services) {
            var obj = services[index];
            var url = 'proxySearch/?q=*&wt=json&indent=on&fq=tag:' + abb + '&fq=tag:"' + encodeURI(obj.name) + '"&rows=' + obj.value + '&fl=name,mdo_id,longitude,latitude&sort=name+asc';
            pushToGoogleAnalytics("Infopanel-search", abb + " " + obj.name, url);
            $.ajax({
                url: url,
                context: { index: index },
                dataType: "json",
                success: function (data) {
                    services[this.index].block = createServiceBlock(data, services[this.index]);

                }
            }).complete(function () {
                complete++;
                if (complete == services.length) {
                    var content = '<div id="map-modal-content-inner">';
                    content += '<div><h2>' + loc_name + '</h2>';
                    content += '<div>' + abb + '/' + building_num + '</div>';
                    content += '</div>';
                    content += '<div id="map-modal-content-inner-right">';

                    if (image)
                        content += '<div class="map-modal-content-item"><img src="' + image + '"  width="200" alter="' + loc_name + '" /></div>';
                    if (link)
                        content += '<div class="map-modal-content-item"><a href="' + link + '" target="_blank">Web site</a></div>';

                    content += handleAvailableAtThisLocation(services);

                    content += '<div class="map-modal-content-item"><a class="moreLocations" href="#" data="' + abb + '" title="find all locations in this building">Find all Locations in this Building</a></div>';

                    content += '</div>';

                    content += '<div id="map-modal-content-inner-left">';
                    if (description) {
                        content += '<div class="map-modal-content-inner-left-service">About This Building</div>';
                        content += '<div class="map-modal-content-inner-left-description">' + description + '</div>';
                    }
                    content += '<div class="map-modal-content-inner-left-service">Popular Locations</div>';
                    content += '<div>';

                    if (services.length > 3)    // it should be greater than 1 since we added women's and men's restroom
                    {
                        content += '<div class="map-modal-content-inner-left-right-box">';
                        for (var i = 0; i < services.length; i++) {
                            if (services[i].block && services[i].display == "right")
                                content += services[i].block;
                        }
                        content += '</div>';
                    }

                    if (services.length > 2)  // it should be greater than 0 since we added women's and men's restroom 
                    {
                        content += '<div class="map-modal-content-inner-left-left-box">';
                        for (var i = 0; i < services.length; i++) {
                            if (services[i].block && services[i].display == "left")
                                content += services[i].block;
                        }
                        content += '</div>';
                        $('.map-modal-whats-in-building-list-li-a').die('click');
                        $('.map-modal-whats-in-building-list-li-a').live('click', function (event) {
                            event.preventDefault();
                            closeInfoWindow = false;

                            var search_url = server + '/proxySearch/?q=*&wt=json&indent=' + indent + '&start=0&rows=100&fq=mdo_id:' + $(this).attr('data-mdo');
                            displayResults(search_url);
                            //closeInfoWindow = false;
                            pushToGoogleAnalytics("PopularLink", $(this).attr('data-mdo') + "-" + $(this).attr('title'), search_url);
                        });
                    }
                    $('.moreLocations').die('click');
                    $('.moreLocations').live('click', function (event) {
                        var url = server + '/proxySearch/?q=*&wt=json&indent=' + indent + '&start=0&rows=100&fq=tag:' + $(this).attr('data') + '&sort=name+asc&fq=-tag:i_bulk';
                        event.preventDefault();
                        closeInfoWindow = true;
                        displayResults(url);
                        pushToGoogleAnalytics("MoreLocations", $(this).attr('data') + "-" + $(this).attr('title'), url);
                    });


                    content += '</div>';
                    if (services.length > 3)    // it should be greater than 1 since we added women's and men's restroom
                        content += '<div class="clear-left"></div>';

                    /*if(description)
                    {
                    content += '<div class="map-modal-content-inner-left-service">About This Building</div>';
                    content += '<div class="map-modal-content-inner-left-description">' + description + '</div>';
                    } */

                    if (history) {
                        content += '<div class="map-modal-content-inner-left-service">History</div>';
                        content += '<div class="map-modal-content-inner-left-description">' + history + '</div>';
                    }

                    content += '</div>';
                    content += '</div>';
                    $('#map-modal-content').html(content);

                    //load the building
                    $('.new-win a').attr('target', '_blank');


                    $('#map-modal').show('slow');
                    $('#map_canvas_over').show();

                    thinking(0);
                }
            });
        }

    });

}

function handleAvailableAtThisLocation(services) {
    var heading = '<div class="map-modal-content-inner-left-service">Available at this location</div>';
    var icons = "";
    $.each(services, function (index, obj) {
        if (obj.name == "ATM")
            icons += '<img src="/images/atm_menu_off.png?' + version + '" title="ATM" alt="ATM" width="20" height="20"/>';
        else if (obj.name == "Women's Restroom") {
            if (parseInt(obj.count) > 0)
                icons += '<img src="/images/womens_restrooms_menu_off.png?' + version + '" title="Women\'s Restroom" alt="Women\'s Restroom" width="20" height="20"/>';

        }
        else if (obj.name == "Men's Restroom") {
            if (parseInt(obj.count) > 0)
                icons += '<img src="/images/mens_restrooms_menu_off.png?' + version + '" alt="Men\'s Restroom" title="Men\'s Restroom" width="20" height="20"/>';
        }

    });
    if (icons && icons.length > 0) {
        heading += '<div class="map-modal-content-available">' + icons + '</div>';
        return heading;
    }
    else
        return icons;

}

function createServiceBlock(data, service) {
    var str = "";
    if (data.response.numFound) {
        if (service.name == "Women's Restroom" || service.name == "Men's Restroom") {
            service.count = data.response.numFound;
            return str;
        }
        else {

            if (service.name == "i_diningservicesplus")
                str = '<div class="map-modal-content-inner-left-box-heading">Food and Dining</div>';
            else
                str = '<div class="map-modal-content-inner-left-box-heading">' + service.name + '</div>';
            str += '<ul>';
            for (var mm in data.response.docs) {
                var mdo = data.response.docs[mm];
                str += '<li><a href="#" title="' + mdo.name + '" class="map-modal-whats-in-building-list-li-a" data-mdo="' + mdo.mdo_id + '">' + mdo.name + '</a></li>';
            }
            str += "</ul>";

        }
        return str;
    }


}


function getMdoContent(i, loc_name) {
    var mdo_url = '/api/mdos/' + i + '/content';
    //var mdo_url = '/api/?mdos-'+i+'-content';

    var link;
    var hours;
    var description;
    var image;
    var keywords;
    var room;
    var building;
    var phone;
    var abbreviation;
    var history;
    var building_num;

    //this will be used to get the tags
    // /proxySearch/?q=*&wt=json&indent=off&start=0&rows=100&fq=mdo_id:8&fl=tag&sort=tag asc

    //mdo_url = '/scripts/demodata.json';

    pushToGoogleAnalytics("Infopanel", loc_name, mdo_url);

    $.getJSON(mdo_url, function (data) {

        if (data) {
            $.each(data.mdo.contents, function (key, val) {

                $.each(val, function (index, value) {
                    if (value.title == "Link") {
                        link = value.contentValue;
                    }
                    if (value.title == "Hours of Operation") {
                        hours = value.contentValue;
                    }
                    if (value.title == "Description") {
                        description = value.contentValue;
                    }
                    if (value.title == "Image") {
                        image = value.contentValue;
                    }
                    if (value.title == "Keywords") {
                        keywords = value.contentValue;
                    }
                    if (value.title == "Room") {
                        room = value.contentValue;
                    }
                    if (value.title == "Building") {
                        building = value.contentValue;
                    }
                    if (value.title == "Phone Number") {
                        phone = value.contentValue;
                    }
                    if (value.title == "Abbreviation") {
                        abbreviation = value.contentValue;
                    }
                    if (value.title == "Building Number") {
                        building_num = value.contentValue;
                    }
                    if (value.title == "History") {
                        history = value.contentValue;
                    }
                });

            });

        }
    }).complete(function () {

        var content = '<div id="map-modal-content-inner">';
        content += '<div id="map-modal-content-inner-right">';
        if (image) {
            content += '<div class="map-modal-content-item"><img src="' + image + '" width="200" alt="' + loc_name + '" title="' + loc_name + '" /></div>';
        }
        if (link) {
            content += '<div class="map-modal-content-item"><a href="' + link + '" target="_blank">Web Site</a></div>';
        }
        if (building) {
            content += '<div class="map-modal-content-item">';
            content += '<a href="/?tags=Building|' + building + '" title="Building Information"  class="building-link">Building Information</a></div>';
        }
        content += '</div>';
        content += '<div id="map-modal-content-inner-left">';
        content += '<h2 id="map-modal-content-header">' + loc_name + '</h2>';

        if (room || building) {
            content += '<div class="map-modal-content-inner-left-service">Located</div>';
            if (building) {
                content += '<div class="map-modal-content-inner-left-description">';
                content += '<a href="/?tags=Building|' + building + '" title="' + building + '"  class="building-link">' + building + '</a>';
            }
            if (room) {
                content += '&nbsp;' + room;
            }
            content += '</div>';

            if (phone) {
                content += '<div class="map-modal-content-inner-left-description">' + phone + '</div>';
            }
        }
        if (description) {
            content += '<div class="map-modal-content-inner-left-service">About</div>';
            content += '<div class="map-modal-content-inner-left-description">' + description + '</div>';
        }
        if (history) {
            content += '<div class="map-modal-content-inner-left-service">History</div>';
            content += '<div class="map-modal-content-inner-left-description">' + history + '</div>';
        }
        if (hours) {
            content += '<div class="map-modal-content-inner-left-service">Hours</div>';
            content += '<div class="map-modal-content-inner-left-description">' + hours + '</div>';
        }
        if (abbreviation) {
            //load the what's in this building
            content += '<div class="map-modal-content-item" id="map-modal-whats-in-building"></div>';
            var whats_in_building_url = server + '/proxySearch/?q=*&wt=json&indent=off&start=0&rows=100&fq=tag:' + abbreviation + '&fq=-tag:i_bulk&fl=name,mdo_id&sort=name%20asc';
            //mdo_url = '/scripts/demodata.json';
            $.getJSON(whats_in_building_url, function (data) {
                if (data && data.response.numFound) {
                    $('#map-modal-whats-in-building').html('<div class="map-modal-content-inner-left-service">Popular Locations</div>');
                    $('<ul id="map-modal-whats-in-building-list"></ul>').appendTo('#map-modal-whats-in-building');
                    $.each(data.response.docs, function (key, val) {
                        $('<li class="map-modal-whats-in-building-list-li"><a title="' + val.name + '" href="/?mdoid=' + val.mdo_id + '" data-mdo="' + val.mdo_id + '" class="map-modal-whats-in-building-list-li-a">' + val.name + '</a></li>').appendTo('#map-modal-whats-in-building-list');
                    });
                }
                else {
                    $('#map-modal-whats-in-building').html('');
                }
            }).complete(function () {
                $('.map-modal-whats-in-building-list-li-a').click(function (event) {
                    event.preventDefault();
                    closeInfoWindow = false;
                    var search_url = server + '/proxySearch/?q=*&wt=json&indent=' + indent + '&start=0&rows=100&fq=mdo_id:' + $(this).attr('data-mdo');
                    displayResults(search_url);
                    //displayMDOInfo(i, 'polygon');
                    pushToGoogleAnalytics("Whatlink", $(this).attr('data-mdo'), search_url);

                });
            });
        }
        if (keywords) {
            content += '<div class="map-modal-content-item">' + keywords + '</div>';
        }
        content += '</div>';
        content += '</div>'; //end of div#map-modal-content-inner
        $('#map-modal-content').html(content);

        //load the building
        $('.new-win a').attr('target', '_blank');

        //load the building
        $('.building-link').click(function (event) {
            event.preventDefault();
            //alert(i);
            closeInfoWindow = false;
            var search_url = server + '/proxySearch/?q=abbreviation:' + building + '&wt=json&indent=' + indent + '&start=0&rows=100&fq=tag:Building';
            displayResults(search_url);
            //getInsideBuildingInfo(i, loc_name, abb);
            //displayMDOInfo(i, 'polygon');
        });

        $('#map-modal').show('slow');
        $('#map_canvas_over').show();

    });
}

function handleInfoContent(obj, prefix) {

    var contentString = '';
    contentString += '<div id="content" class="center-content">';
    contentString += '<div id="siteNotice"></div>';
    contentString += '<div id="firstHeading" class="links-infowindow-title"><h2><a href="javascript:moreInfo(' + (obj.id) + ',\'' + stripQuotes(encodeURI(obj.title)) + '\', \'' + obj.abb + '\')" title="More info">' + obj.title + '</a></h2></div>';
    contentString += '<div id="bodyContent">';

    contentString += '<div class="info-window-description">' + obj.description;
    contentString += '</div>';
    //contentString += '<div class="info-window-right">';
    if (obj.img) {
        contentString += '<a href="javascript:moreInfo(' + (obj.id) + ',\'' + stripQuotes(encodeURI(obj.title)) + '\', \'' + obj.abb + '\')" title="More info"><img  src="' + obj.img + '" width="100" alt="' + obj.title + '" /></a>';

    }
    contentString += '<div class="info-window-link"><a href="javascript:moreInfo(' + (obj.id) + ',\'' + stripQuotes(encodeURI(obj.title)) + '\', \'' + obj.abb + '\')" title="More info">More info</a></div>';
    //contentString += '</div>';

    //contentString += '<div class="info-window-left">';
    //contentString += '<div class="info-window-description">' + obj.description;
    //contentString += '</div>';
    //contentString += '</div>';

    contentString += '</div>';
    contentString += '</div>';
    var mapcenter = map.getCenter();
    infowindow.setContent(contentString);
    infowindow.setOptions(infowindowOptions);

    var latlng = new google.maps.LatLng(obj.lat, obj.lng);
    map.panTo(latlng);
    infowindow.setPosition(latlng);
    current_infowindow = prefix + '-' + obj.id;
    if ($('#map-modal').is(":visible")) {
        moreInfo(obj.id, obj.title, obj.abb);
    }
    infowindow.open(map);
    pushToGoogleAnalytics("Infowindow", obj.title, "no url");

}

function showPolyInfo(event) {
    //var vertices = this.getPath();

    handleInfoContent(this, 'p');
}

function showMarkerInfo(event) {
    handleInfoContent(this, 'm');
}



function parsePolygonPath(path) {
    var mvcArray = new google.maps.MVCArray();
    var oldPath = path;
    var pointList = oldPath.split("|");
    for (var index = 0; index < pointList.length; index++) {
        var latlngArray = pointList[index].split(",");
        var lat = trimStr(latlngArray[0]);
        var lng = trimStr(latlngArray[1]);
        var latlng = new google.maps.LatLng(lat, lng);
        mvcArray.push(latlng);
    }
    return mvcArray;
}

function trimStr(oneStr) {
    return oneStr.replace(/^\s+|\s+$/g, '');
}

// Read a page's GET URL variables and return them as an associative array.
function getUrlVars() {
    return parseURL(window.location.href);
}

function parseURL(aURL) {
    var vars = [], hash;
    var hashes = aURL.slice(aURL.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        if (hash[0] == "tags") {
            hash[1] = hash[1].replace("%7C", "|");
            hash[1] = hash[1].replace("%257C", "|");
            hash[1] = hash[1].replace("%7c", "|");
            hash[1] = hash[1].replace("%257c", "|");
        }
        vars[hash[0]] = hash[1];
    }
    return vars;

}

//move to the MDO and display the info 
function displayMDOInfo(mdo_id, mdo_type) {

    mdo_id = parseInt(mdo_id);
    current_infowindow = "m-" + mdo_id;
    $("#share-panel").slideUp('300');

    if (mdo_type == "polygon") {
        google.maps.event.trigger(thisPoly[mdo_id], "click");
    }
    if (mdo_type == "marker") {
        google.maps.event.trigger(thisMarker[mdo_id], "click");
    }

}

function getAlpha(i) {
    var str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    return str.charAt(i);
}
function stripQuotes(x) {
    x = x.replace(/[']/g, '\\\'');
    x = x.replace(/["]/g, '\\\"');
    return x;
};

//reset the query start number and row number
function resetStartNum() {
    n_results_start = 0;
    n_results_rows = 10;
}

// Removes the overlays from the map, but keeps them in the array
function clearOverlays() {
    if (markersArray) {
        for (i in markersArray) {
            markersArray[i].setMap(null);
        }
    }
}

// Shows any overlays currently in the array
function showOverlays() {
    if (markersArray) {
        for (i in markersArray) {
            markersArray[i].setMap(map);
        }
    }
}

// Deletes all markers in the array by removing references to them
function deleteOverlays() {
    if (markersArray) {
        for (i in markersArray) {
            markersArray[i].setMap(null);
        }
        markersArray.length = 0;
    }
}

function resultsNav(start, rows, numfound, search_url) {

    var display_start = start + 1;
    var display_end = rows + start;

    //alert(start+'-'+rows+'-'+numfound+'-'+search_url);
    if (display_end > numfound) {
        display_end = numfound;
    }
    if (numfound > rows) {
        var results_nav_link = '';
        //alert(search_url);
        var hashes = search_url.slice(search_url.indexOf('?') + 1).split('&');

        var hash;
        $.each(hashes, function (key, val) {
            hash = val.split('=');

            if (hash[0] != 'start' && hash[0] != 'rows' && hash[0] != 'show') {
                results_nav_link += '&' + hash[0] + '=' + decodeURI(hash[1]);
            }

        });
        //alert(results_nav_link);

        //alert(hashes.legnth);
        /*
        for(var i = 0; i < hashes.length; i++)
        {
        //proxySearch/?q=*&wt=json&indent='+indent+'&fq=tag:"Food"
        alert(hashes[i]);
        }
        */
        var prev_start = parseInt(start - rows);
        var next_start = parseInt(start + rows);
        var service_show_all = server + '/proxySearch/?show=all' + encodeURI(results_nav_link) + '&start=0&rows=' + numfound;
        var prevClass = "results-nav-controls-prev";
        var nextClass = "results-nav-controls-next";

        if (prev_start < 0) {
            var service_show_prev = '#';
            prevClass = "results-nav-controls-noaction";
        }
        else {
            var service_show_prev = server + '/proxySearch/?show=prev' + encodeURI(results_nav_link) + '&start=' + parseInt(prev_start) + '&rows=100';
        }
        if (next_start >= numfound) {
            var service_show_next = '#';
            nextClass = "results-nav-controls-noaction";
        }
        else {
            var service_show_next = server + '/proxySearch/?show=next' + encodeURI(results_nav_link) + '&start=' + parseInt(next_start) + '&rows=100';
        }
        var content = '';
        if (marker_override)
            var results_nav_controls = '<span onclick="displayResults(\'' + service_show_all + '\', false, true)" class="results-nav-controls-all" title="Show all">Show all</span> | <span onclick="displayResults(\'' + service_show_prev + '\', false, true)" class="' + prevClass + '" title="Previous">Prev</span> | <span onclick="displayResults(\'' + service_show_next + '\', false, true)" class="' + nextClass + '" title="Next">Next</span>';
        else
            var results_nav_controls = '<span onclick="displayResults(\'' + service_show_all + '\')" class="results-nav-controls-all" title="Show all">Show all</span> | <span onclick="displayResults(\'' + service_show_prev + '\')" class="' + prevClass + '" title="Previous">Prev</span> | <span onclick="displayResults(\'' + service_show_next + '\')" class="' + nextClass + '" title="Next">Next</span>';

        content += '<div class="results-nav-controls">' + results_nav_controls + '</div>';
        content += '<div class="results-nav-count">Displaying ' + display_start + ' - ' + display_end + '</div>';
        return '<div class="results-nav">' + content + '</div>';
    } else {
        content = '<div class="results-nav-count">Displaying ' + display_start + ' - ' + display_end + '</div>';
        return '<div class="results-nav">' + content + '</div>';
    }
}

//display the results - pass it a search URL and an optional zoom override.
//zoom override will disable the zoom to fit all markers and enable better deep linking
//marker override will return the markers without letters.  This is mainly for parking lots.
function displayResults(search_url, zoom_override, marker_override) {

    if (search_url != '#') {
        var items = [];
        var n_index = 0;
        var marker_color = 'dk-blue';
        var marker_highlight_color = 'lt-blue';

        $('#result-wrapper').fadeOut(300, function () { $(this).remove(); });

        if (closeInfoWindow == true) {
            infowindow.close();
            $('#map-modal').hide();
        }
        deleteOverlays();
        var search_results = '<div id="result-count">No Results Found</div>';
        $.getJSON(search_url, function (data) {

            if (data.response.numFound) {

                //bounds for the search results
                var search_bounds = new google.maps.LatLngBounds();

                //close the share panel
                if ($('#share-panel').is(':visible')) {
                    $('#share-panel').slideUp('slow');
                    $('#map_canvas_over').hide();
                }

                var result_results = "results";
                if (data.response.numFound == 1) {
                    result_results = "result";
                }
                search_results = '<div id="result-wrapper">';
                search_results += '<div id="result-count"><div id="reset-search-container"><a href="#" id="reset-search-link" title="Reset">Reset</a></div>' + data.response.numFound + ' ' + result_results + ' found</div>';


                //search nav
                //alert("rows: " + data.responseHeader.params.rows);
                search_results += resultsNav(parseInt(data.response.start), parseInt(data.responseHeader.params.rows), parseInt(data.response.numFound), search_url);

                //set the result start and num results for deep linking
                n_results_start = parseInt(data.response.start);
                n_results_rows = parseInt(data.responseHeader.params.rows);

                var letter_index = 0;
                var even_odd = "odd";
                $.each(data.response.docs, function (key, val) {
                    //alert(val.name);
                    var mdo_type;
                    var object_id;

                    var marker_suffix = '';

                    if (!marker_override) {
                        marker_suffix = getAlpha(letter_index);
                    }

                    if (val.polygon_id) {
                        mdo_type = "polygon";
                        object_id = val.polygon_id;
                    }
                    else {
                        mdo_type = "marker";
                        object_id = val.marker_id;
                    }
                    if (even_odd == "even")
                        search_results += '<div class="search-result-container search-result-' + even_odd + '" id="n-' + object_id + '" style="background:url(../images/results-bg-even.gif?' + version + ') repeat-x scroll 0 0 transparent;">';
                    else
                        search_results += '<div class="search-result-container search-result-' + even_odd + '" id="n-' + object_id + '">';
                    search_results += '		<div class="search-result-marker" onclick="displayMDOInfo(' + object_id + ', \'' + mdo_type + '\');"><img src="/images/markers/' + marker_color + '_Marker' + marker_suffix + '.png?' + version + '" alt="marker-' + getAlpha(letter_index) + '" title="' + val.name + '" width="20" height="34" id="Marker' + getAlpha(letter_index) + '"/></div>';
                    search_results += '		<div class="search-result-info">';
                    search_results += '			<div class="search-result-info-name" onclick="displayMDOInfo(' + object_id + ', \'' + mdo_type + '\');" title="' + val.name + '">' + val.name + '</div>';
                    search_results += '			<div class="search-result-info-description">' + val.description + '</div>';
                    search_results += '		</div>';

                    search_results += '		<div class="clearer"></div>';
                    search_results += '</div>';

                    var markerLatlng = new google.maps.LatLng(val.latitude, val.longitude);
                    //add the lat and lng to search bounds
                    search_bounds.extend(markerLatlng);
                    var abb = "";
                    if (val.abbreviation)
                        abb = val.abbreviation;
                    thisMarker[val.mdo_id] = new google.maps.Marker({
                        position: markerLatlng,
                        map: map,
                        //title: 'Marker'+getAlpha(letter_index)+'-m',
                        icon: server + '/images/markers/' + marker_color + '_Marker' + marker_suffix + '.png?' + version,
                        title: val.name,
                        description: val.description,
                        shadow: shadow,
                        lat: val.latitude,
                        lng: val.longitude,
                        id: val.mdo_id,
                        img: val.image,
                        abb: abb
                    });

                    markersArray.push(thisMarker[val.mdo_id]);
                    //add click function to the markers
                    google.maps.event.addListener(thisMarker[val.mdo_id], 'click', showMarkerInfo);

                    /*if( $('#map-modal').is(":visible") ) {
                    moreInfo(val.mdo_id,val.name, abb);
                    } */

                    if (even_odd == 'odd') {
                        even_odd = 'even';
                    }
                    else {
                        even_odd = 'odd';
                    }
                    n_index++;
                    letter_index++;

                });
                search_results += resultsNav(parseInt(data.response.start), parseInt(data.responseHeader.params.rows), parseInt(data.response.numFound), search_url);

                search_results += '</div>'; //end of result-wrapper

                //if the zoom is not overridden, zoom in or out to fit all markers
                if (!zoom_override) {
                    //fit the map bounds
                    map.fitBounds(search_bounds);
                    //if the zoom is too high zoom out
                    if (map.getZoom() > 18) {
                        map.setZoom(18);
                    }

                }


                //if there is a single result pop open the info window
                if (data.response.numFound === 1) {
                    if (data.response.docs[0].polygon_id) {
                        displayMDOInfo(data.response.docs[0].polygon_id, 'polygon');
                        //items[] = data.response.docs[0].marker_id;
                    }
                    if (data.response.docs[0].marker_id) {
                        displayMDOInfo(data.response.docs[0].marker_id, 'marker');
                        //items[] = data.response.docs[0].marker_id;
                    }
                    //items[] = data.response.docs[0].marker_id; 
                }


            }
            $('#sidebar-first-dynamic').html(search_results);
            $('div.search-result-info-description').expander({
                slicePoint: 80,  // default is 100
                expandText: '[...]', // default is 'read more...'
                collapseTimer: 5000, // re-collapses after 5 seconds; default is 0, so no re-collapsing
                userCollapseText: '[^]'  // default is '[collapse expanded text]'
            });


            $("div.search-result-container").hover(
  					function () {
  					    marker_num = $(this).attr('id');
  					    marker_num = parseInt(marker_num.substring(2));
  					    marker_id = $(this).find('img').attr("id");
  					    if (marker_override) {
  					        marker_id = "Marker";
  					    }
  					    //alert("/images/markers/"+marker_highlight_color+"_"+marker_id+".png");
  					    $(this).find('img').attr("src", "/images/markers/" + marker_highlight_color + "_" + marker_id + ".png?" + version);
  					    thisMarker[marker_num].setIcon("/images/markers/" + marker_highlight_color + "_" + marker_id + ".png?" + version);
  					},
  					function () {
  					    $(this).removeClass("hover");
  					    //alert("/images/markers/"+marker_color+"_"+marker_id+".png");
  					    $(this).find('img').attr("src", "/images/markers/" + marker_color + "_" + marker_id + ".png?" + version);
  					    //$('#'+marker_id+'-m').attr("src", "/images/markers/orange_"+marker_id+".png");
  					    thisMarker[marker_num].setIcon("/images/markers/" + marker_color + "_" + marker_id + ".png?" + version);
  					}
				);


            $('#reset-search-link').click(function (event) {
                event.preventDefault();
                deleteOverlays();
                tag_text = '';
                $('#result-wrapper').slideUp(300, function () { $(this).remove(); });

                //close the info window if it is open
                infowindow.close();
                if ($('#map-modal').is(':visible')) {
                    $('#map-modal').slideUp('slow');
                    $('#map_canvas_over').hide();
                }
                if ($('#share-panel').is(':visible')) {
                    $('#share-panel').slideUp('slow');
                    $('#map_canvas_over').hide();
                }
                resetStartNum();

                $('#search-box').val('');
                return false;
            });



        }).complete(function () {
            $('#search-box').autocomplete('close');
            thinking(0);
        });

        //close the autocomplet box if it is still open

        //alert (search_results);
        //$('#sidebar-first-inner').replaceWith(search_results);

        //alert(items.length);
        /*
        $('<ul/>', {
        'class': 'my-new-list',
        html: items.join('')
        }).appendTo('#sidebar-first-inner');
        */
    }
}

//search term takes the search box value and an optional zoom override flag
function searchTerm(search_box_val, zoom_override) {
    if (search_box_val) {
        var search_url = server + '/proxySearch/?q=' + search_box_val + '&q.op=AND&wt=json&indent=' + indent;
        //search_url += '&fq=-tag:Restroom';
        //search_url += '&fq=-tag:"Bike+Rack"';
        search_url += '&fq=-tag:i_bulk';

        if (n_results_start) {
            search_url += '&start=' + n_results_start;
        }
        else {
            search_url += '&start=0';
        }
        if (n_results_rows) {
            search_url += '&rows=' + n_results_rows;
        }
        if (zoom_override) {
            displayResults(search_url, 1); //this is a deep link override automatic zooming to fit all search results
        }
        else {
            displayResults(search_url);
        }
        pushToGoogleAnalytics("Search", search_box_val, search_url);
    }
}

function showPreset(preset_id, tags) {
   // alert(preset_id + ', ' + tags);
    tag = tags.replace(/%22/g, "");
    marker_override = false;

    if (preset_id && (preset_id == 'p1' || preset_id == 'p2' || preset_id == 'p3'))
        marker_override = true;

    thinking(1);
    var search_url = server + '/proxySearch/?q=*&wt=json&indent=' + indent + '&fq=tag:"' + tag + '"&rows=100&sort=name+asc';
    displayResults(search_url, false, marker_override);
    pushToGoogleAnalytics("Quick Search", tags, search_url);
}

function LocateControl(controlDiv, map) {
    controlDiv.style.padding = '5px';

    var controlUI = document.createElement('DIV');
    controlUI.style.backgroundColor = 'white';
    controlUI.style.borderStyle = 'solid';
    controlUI.style.borderWidth = '2px';
    //controlUI.style.position = 'absolute';
    //controlUI.style.zIndex = 10;
    //controlUI.style.top = '5px';
    //controlUI.style.right = '90px';
    controlUI.style.cursor = 'pointer';
    controlUI.style.textAlign = 'center';
    controlUI.id = 'locateMe';
    controlUI.title = 'Click to toggle Location Service';
    controlDiv.appendChild(controlUI);

    var controlText = document.createElement('DIV');
    controlText.style.fontFamily = 'Arial,sans-serif';
    controlText.style.fontSize = '12px';
    controlText.style.paddingLeft = '10px';
    controlText.style.paddingRight = '10px';
    controlText.innerHTML = 'Locate Off';
    controlText.setAttribute('id', 'locateText');

    controlUI.appendChild(controlText);

    google.maps.event.addDomListener(controlUI, 'click', function () {
        if (currentLocationMarker == null)
            setupCurrentLocationMarker(map, o_initial_location);

        if (locateMe == null) {

            //locate_timer=setTimeout(locateUserOnMap,3000);
            locateUserOnMap();
            $('#locateText').html('Locate On');
            currentLocationMarker.setMap(map);
            var latlng = currentLocationMarker.getPosition();
            map.panTo(latlng);
            infowindow.close();
            locateMe = "findMe";
        }
        else {
            //clearTimeout(locate_timer);
            //locate_timer = null;
            locateMe = null;
            $('#locateText').html('Locate Off');
            currentLocationMarker.setMap(null);
        }
    });
}

thinking = function (status) {
    if (status) {
        $('#thinking-box-image').attr('src', server + '/images/ajax-loader-32-32.gif?' + version);
    }
    else {
        $('#thinking-box-image').attr('src', server + '/images/blank.gif?' + version);
    }
}

function getLandMarkers(search_url, markerArray, iconUrl, canClick) {

    var search_bounds = new google.maps.LatLngBounds();
    $.getJSON(search_url, function (data) {
        if (data.response.numFound) {
            var markerLatlng;
            var counter = 0;
            $.each(data.response.docs, function (key, val) {
                markerLatlng = new google.maps.LatLng(val.latitude, val.longitude);
                search_bounds.extend(markerLatlng);
                markerArray[counter] = new google.maps.Marker({
                    position: markerLatlng,
                    map: map,
                    icon: iconUrl,
                    title: val.name,
                    description: val.description,
                    id: val.mdo_id,
                    img: val.image,
                    lat: val.latitude,
                    lng: val.longitude,
                    clickable: canClick
                });

                if (canClick)
                    google.maps.event.addListener(markerArray[counter], 'click', showMarkerInfo);
                counter++;
            });
        }
    }).complete(function () {
        thinking(0);
        if (markerArray.length > 0)
            map.fitBounds(search_bounds);
        else
            alert("not found : 0");
        //if the zoom is too high zoom out
        if (map.getZoom() > 18) {
            map.setZoom(18);
        }
        //alert("sise of array: " + markerArray.length);
    });

}

function handleLandMarker(search_url, markerArray, icon, clickable, marker_type) {

    if (markerArray.length > 0) {
        var search_bounds = new google.maps.LatLngBounds();

        for (var i in markerArray) {
            markerArray[i].setMap(map);
            search_bounds.extend(markerArray[i].getPosition());

        }
        thinking(0);
        map.fitBounds(search_bounds);
        if (map.getZoom() > 18) {
            map.setZoom(18);
        }
        pushToGoogleAnalytics("Landmark", marker_type, "reuse resource");

    }
    else {
        getLandMarkers(search_url, markerArray, icon, clickable);
        pushToGoogleAnalytics("Landmark", marker_type, search_url);
    }

}

placeGroupMarkers = function (search_url, marker_type) {

    var icon = server + '/images/markers/' + marker_type + '.png?' + version;

    if (marker_type == 'bike_racks_marker') {
        handleLandMarker(search_url, bikeMarker, icon, false, marker_type);
    }
    else if (marker_type == 'womens_restrooms_marker') {
        handleLandMarker(search_url, restroomWomensMarker, icon, false, marker_type);
    }
    else if (marker_type == 'mens_restrooms_marker') {
        handleLandMarker(search_url, restroomMensMarker, icon, false, marker_type);

    }
    else if (marker_type == 'bus_stops_marker') {
        handleLandMarker(search_url, busstopsMarker, icon, true, marker_type);
    }
    else if (marker_type == 'atm_marker') {
        handleLandMarker(search_url, atmsMarker, icon, true, marker_type);
    }


}

function removeLandMarker(markerArray) {
    for (var i in markerArray)
        markerArray[i].setMap(null);
}

removeGroupMarkers = function (marker_type) {

    if (marker_type == 'bike_racks_marker') {
        removeLandMarker(bikeMarker);
    }
    else if (marker_type == 'womens_restrooms_marker') {
        removeLandMarker(restroomWomensMarker);
    }
    else if (marker_type == 'mens_restrooms_marker') {
        removeLandMarker(restroomMensMarker);
    }
    else if (marker_type == 'bus_stops_marker') {
        removeLandMarker(busstopsMarker);
    }
    else if (marker_type == 'atm_marker') {
        removeLandMarker(atmsMarker);
    }
    pushToGoogleAnalytics("Landmark", marker_type, "turn off");
}


$(document).ready(function () {
    //kick it off
    //setUpGoogleAnalytics();

    map.initialize();

    google.maps.event.addListener(map, 'maptypeid_changed', function () {
        var type = map.getMapTypeId();
        if (type == google.maps.MapTypeId.ROADMAP) {
            //tileMapType.opacity = 1.0;
            map.overlayMapTypes.insertAt(0, tileMapType);

        }
        else {
            map.overlayMapTypes.setAt(0, null);
        }
    });


    $("#links-share").click(function () {
        var mapcenter = map.getCenter();
        //base url passed from the html page.  may want to grab it from the browser
        var linkParams = '?zoom=' + map.getZoom() + '&lat=' + mapcenter.lat() + '&lng=' + mapcenter.lng() + '';

        if (infowindow.getMap()) {
            linkParams += '&open=' + current_infowindow;
        }
        if ($('#search-box').val()) {
            linkParams += '&q=' + $('#search-box').val();
        }
        if (tag_text) {
            //alert("tag: " + tag_text);
            linkParams += '&tags=' + tag_text;
        }
        if (n_results_start) {
            linkParams += '&start=' + n_results_start;
        }
        else {
            linkParams += '&start=0';
        }
        if (n_results_rows) {
            linkParams += '&rows=' + n_results_rows;
        }
        var deepLink = base_url + '/' + linkParams;
        var iframe = '<iframe style="width: 550px; height: 450px;" src="' + base_url + '/embed.php' + linkParams + '&displaylink=true" title="RIT Campus Map" scrolling="no" frameborder="0"></iframe>';

        $("#share-address").val(deepLink);
        $("#email-address").attr("href", "mailto:?subject=RIT Map Link&body=" + encodeURIComponent(deepLink));
        $("#embed-address").val(iframe);


        if ($('#share-panel').is(':hidden')) {
            $('#share-panel').show();
            $('#map_canvas_over').show();
        }
        else {
            $('#share-panel').slideUp('fast');
            if ($('#map-modal').is(':hidden')) {
                $('#map_canvas_over').slideUp();
            }
        }
        return false;
    });

    $('#map-modal-close').click(function () {
        $('#map-modal').hide('slow');
        $('#map_canvas_over').hide();
    });

    $('#map_canvas_over').click(function () {
        $('#map-modal').hide('slow');
        $("#share-panel").slideUp('300');
        $("#map_canvas_over").hide();
    });

    function handleSearchForm() {
        var search_term = $('#search-box').val();
        search_term = trimStr(search_term);

        if (search_term.length == 0) {
            alert("Please enter search keyword");
        }
        else {
            infowindow.close();
            $("#map-modal").hide();
            resetStartNum();
            searchTerm(search_term);
            tag_text = '';
            thinking(1);

        }

    }

    $('#search-submit').click(function () {
        handleSearchForm();

    });

    $("form").bind("keypress", function (e) {
        if (e.keyCode == 13) {

            $('#search-box').autocomplete('close');
            $('#sidebar-first').focus();
            handleSearchForm();
            return false;
        }
    });

    $('.preset-link').click(function (event) {
        event.preventDefault();
        closeInfoWindow = true;

        infowindow.close();
        $('#map-modal').hide();

        $('#search-box').val('');
        var preset_id = $(this).attr('id');
        var param = parseURL($(this).attr("href"));
        tag_text = param["tags"];
        showPreset(preset_id, param["tags"]);

    });

    $('#links-print').click(function (event) {
        event.preventDefault();

        //we may need to close the info window before printing
        //infowindow.close();

        //alert(tag_id);
        var mapcenter = map.getCenter();
        //base url passed from the html page.  may want to grab it from the browser
        var linkParams = '?zoom=' + map.getZoom() + '&lat=' + mapcenter.lat() + '&lng=' + mapcenter.lng() + '';

        if (infowindow.getMap()) {
            linkParams += '&open=' + current_infowindow;
        }
        if ($('#search-box').val()) {
            linkParams += '&q=' + $('#search-box').val();
        }
        if (tag_text) {
            linkParams += '&tags=' + tag_text;
        }
        if (n_results_start) {
            linkParams += '&start=' + n_results_start;
        }
        else {
            linkParams += '&start=0';
        }
        if (n_results_rows) {
            linkParams += '&rows=' + n_results_rows;
        }
        var deepLink = base_url + '/print.php' + linkParams;
        window.open(deepLink);

        pushToGoogleAnalytics("Print", tag_text, deepLink);
        return false;

    });

    $('#additional-landmarks-toggle-bikes').click(function (event) {
        $('#map-modal').hide();
        infowindow.close();
        if ($(this).attr('class') == 'markers-off') {
            thinking(1);

            var url = server + '/proxySearch/?q=*&wt=json&indent=' + indent + '&start=0&rows=1000&fq=tag:' + encodeURI("Bike+Rack") + '&fl=name,mdo_id,longitude,latitude';
            placeGroupMarkers(url, 'bike_racks_marker');
            $(this).removeClass('markers-off').addClass('markers-on');
            $('img', this).attr('src', server + '/images/bike_racks_menu.png?' + version);
            $('#bikeCheckBox').attr('checked', true);
        }
        else {
            removeGroupMarkers('bike_racks_marker');
            $(this).removeClass('markers-on').addClass('markers-off');
            $('img', this).attr('src', server + '/images/bike_racks_menu_off.png?' + version);
            $('#bikeCheckBox').attr('checked', false);
        }
    });
    $('#additional-landmarks-toggle-restroom-womens').click(function (event) {
        $('#map-modal').hide();
        infowindow.close();
        if ($(this).attr('class') == 'markers-off') {
            thinking(1);
            var url = server + '/proxySearch/?q=*&wt=json&indent=' + indent + '&start=0&rows=1000&fq=tag:' + encodeURI("Women's+Restroom") + '&fl=name,mdo_id,longitude,latitude';
            placeGroupMarkers(url, 'womens_restrooms_marker');
            $(this).removeClass('markers-off').addClass('markers-on');
            $('img', this).attr('src', server + '/images/womens_restrooms_menu.png?' + version);
            $('#womenCheckBox').attr('checked', true);
        }
        else {
            removeGroupMarkers('womens_restrooms_marker');
            $(this).removeClass('markers-on').addClass('markers-off');
            $('img', this).attr('src', server + '/images/womens_restrooms_menu_off.png?' + version);
            $('#womenCheckBox').attr('checked', false);
        }
    });
    $('#additional-landmarks-toggle-restroom-mens').click(function (event) {
        $('#map-modal').hide();
        infowindow.close();
        if ($(this).attr('class') == 'markers-off') {
            thinking(1);
            var url = server + '/proxySearch/?q=*&wt=json&indent=' + indent + '&start=0&rows=1000&fq=tag:' + encodeURI("Men's+Restroom") + '&fl=name,mdo_id,longitude,latitude';
            placeGroupMarkers(url, 'mens_restrooms_marker');
            $(this).removeClass('markers-off').addClass('markers-on');
            $('img', this).attr('src', server + '/images/mens_restrooms_menu.png?' + version);
            $('#menCheckBox').attr('checked', true);
        }
        else {
            removeGroupMarkers('mens_restrooms_marker');
            $(this).removeClass('markers-on').addClass('markers-off');
            $('img', this).attr('src', server + '/images/mens_restrooms_menu_off.png?' + version);
            $('#menCheckBox').attr('checked', false);
        }
    });

    $('#additional-landmarks-toggle-busstops').click(function (event) {
        $('#map-modal').hide();
        infowindow.close();
        if ($(this).attr('class') == 'markers-off') {
            thinking(1);
            placeGroupMarkers(server + '/proxySearch/?q=*&wt=json&indent=' + indent + '&start=0&rows=1000&fq=tag:"' + encodeURI("Bus Stop") + '"', 'bus_stops_marker');
            $(this).removeClass('markers-off').addClass('markers-on');
            $('img', this).attr('src', server + '/images/bus_stops_menu.png?' + version);
            $('#busstopsCheckBox').attr('checked', true);
        }
        else {
            removeGroupMarkers('bus_stops_marker');
            $(this).removeClass('markers-on').addClass('markers-off');
            $('img', this).attr('src', server + '/images/bus_stops_menu_off.png?' + version);
            $('#busstopsCheckBox').attr('checked', false);
        }
    });

    $('#additional-landmarks-toggle-atms').click(function (event) {
        $('#map-modal').hide();
        infowindow.close();
        if ($(this).attr('class') == 'markers-off') {
            thinking(1);
            placeGroupMarkers(server + '/proxySearch/?q=*&wt=json&indent=' + indent + '&start=0&rows=1000&fq=tag:"' + encodeURI("ATM") + '"', 'atm_marker');
            $(this).removeClass('markers-off').addClass('markers-on');
            $('img', this).attr('src', server + '/images/atm_menu.png?' + version);
            $('#atmsCheckBox').attr('checked', true);
        }
        else {
            removeGroupMarkers('atm_marker');
            $(this).removeClass('markers-on').addClass('markers-off');
            $('img', this).attr('src', server + '/images/atm_menu_off.png?' + version);
            $('#atmsCheckBox').attr('checked', false);
        }
    });

    $('#bikeCheckBox').attr('checked', false).attr('disabled', false);
    $('#busstopsCheckBox').attr('checked', false).attr('disabled', false);
    $('#womenCheckBox').attr('checked', false).attr('disabled', false);
    $('#menCheckBox').attr('checked', false).attr('disabled', false);
    $('#atmsCheckBox').attr('checked', false).attr('disabled', false);


    $('#quickSearches').click(function () { collapse("#quickSearches", "#quickSearchesBox"); });
    $('#additionalLandmarks').click(function () { collapse("#additionalLandmarks", "#additionalLandmarksBox"); });
    $('#helpfeedback').click(function () { collapse("#helpfeedback", "#helpfeedbackBox"); });


    //auto complete search form
    $('#search-box').autocomplete({ source: "/proxySearch/autocomplete.php", minLength: 1 });

});

function collapse(clickBox, collapseBox) {

    if ($(collapseBox).is(":hidden")) {
        $(clickBox).find("img").attr('src', "/images/arrow_down.png?" + version);
        $(collapseBox).slideDown();

    }
    else {
        $(clickBox).find("img").attr('src', "/images/arrow_right.png?" + version);
        $(collapseBox).slideUp();
    }
}
